import AxiosManage from "../Steam/AxiosMethod/AxiosManage";
import WsData from "../Steam/WsData";
let instance: WsServer = null;
export default class WsServer {
    private webServer: WebSocket;
    private wsData: WsData;
    private _wsEvent: Array<Function> = new Array<Function>();
    public onmessage: Function;
    constructor() {
        this.webServer = new WebSocket("ws://" + AxiosManage.WsUrl);
        this.wsData = new WsData("udp", null)
        this.webServer.onopen = () => {
            this.webServer.send(JSON.stringify(this.wsData));
            this.webServer.onmessage = (res) => {
                // this._wsEvent.forEach(element => {
                //     element(res.data);
                // });
                for (let event in this._wsEvent) {
                    this._wsEvent[event](res.data);
                }
            }
        }
    }

    public addEvent(key:string,event: Function) {
        this._wsEvent[key]=event;
    }

    public removeEvent(key: string) {
        // this._wsEvent.splice(this._wsEvent.indexOf(event), 1);
        delete this._wsEvent[key];
    }

    // private onMessage(callback: Function, wsData: WsData): void {
    //     callback && callback(wsData)
    // }

    // private GeneraRandom() {
    //     return Math.random() * 10000;
    // }
    public static get Instance() {
        if (instance === null) {
            instance = new WsServer();
        }
        return instance;
    }
}

